#! /bin/env python
# -*- coding: utf-8 -*-
#
# $Id: fotoalba.py 23 2008-01-20 15:00:06Z georgo10 $

from PyQt4 import QtCore,QtGui
from fotoalba_main import Ui_fotoalba_main
from anakreon import *
from mylog import *
import sys, shutil, os, random, urllib

faInst = False
mylog.debug = True
IMAGE_ID = 1
actualFilename = ""
entropy = random.randint(0,10000)
imageList = []

def upload():
	faInst.kernel.aid = faInst.kernel.albums[ui.albumBox.currentIndex()][0]
	maximum = imageList.__len__()
	ui.uploadProgress.setMaximum(imageList.__len__())
	try:
		while True:
			faInst.kernel.image = imageList.pop(0)
			faInst.uploadImage()
			ui.uploadProgress.setValue(maximum - imageList.__len__())
	except IndexError:
		pass
	except:
		raise

def tryBrowseImage(self, event):
	global actualFilename
	if event.mimeData().hasUrls() == True:
		tryFileName = event.mimeData().urls()[0].toLocalFile()
		if os.path.exists(tryFileName):
			actualFilename = tryFileName
			ui.photoEdit.setText(actualFilename)
			ui.imagePreview.setPixmap(QtGui.QPixmap(actualFilename))
			ui.addImageButton.setEnabled(True)
			ui.titleEdit.setSelection(0, len(ui.titleEdit.text()))
			ui.titleEdit.setFocus() # TODO: Why don't work?

def browseImage():
	global actualFilename
	tryFileName = QtGui.QFileDialog().getOpenFileName(window, u"Vyberte fotku", "/home/georgo/", u"Obrázky (*.png *.jpg *.jpeg *.gif)")
	if os.path.exists(tryFileName):
		actualFilename = tryFileName
		ui.photoEdit.setText(actualFilename)
		ui.imagePreview.setPixmap(QtGui.QPixmap(actualFilename))
		ui.addImageButton.setEnabled(True)
		ui.titleEdit.setSelection(0, len(ui.titleEdit.text()))
		ui.titleEdit.setFocus()

def acceptImage():
	global IMAGE_ID, actualFilename, imageList
	newFilename = "/tmp/image-%d-%d" %(entropy, IMAGE_ID)
	shutil.copyfile(actualFilename, newFilename)
	log(u"Kopíruji %s jako %s" %(actualFilename, newFilename), 0)
	IMAGE_ID += 1
	imageResize = ui.resizeCombo.currentIndex()
	if imageResize == 1:
		resize = 1600
		quality = 85
		sizeTo = u"Velké"
	elif imageResize == 2:
		resize = 1024
		quality = 80
		sizeTo = u"Střední"
	elif imageResize == 3:
		resize = 800
		quality = 70
		sizeTo = u"Malé"
	else:
		resize = 0
		sizeTo = u"Původní velikost"
	
	os.system("convert %s -size '192x192>' -resize '192x192>' -thumbnail '192x192>' %s_t" %(newFilename, newFilename))
	
	if resize > 0:
		ret = os.system("mogrify -auto-orient -quality %d%% -size '%dx%d>' -resize '%dx%d>' %s" %(quality, resize, resize, resize, resize, newFilename))
		if ret:
			log(u"Při změně velikosti obrázku došlo k chybě. Return code %d" %(ret), 0)
			return
	
	title = ui.titleEdit.text().__str__()
	desc = ui.descEdit.text().__str__()
	
	newPhoto = {
		'file': newFilename,
		'title': title,
		'desc': desc
	}
	
	item = QtGui.QListWidgetItem()
	item.setText(title)
	item.setIcon(QtGui.QIcon("%s_t" %(newFilename)))
	item.setToolTip(u"<center><img src=\"%s_t\" /><br/>Popis: %s<br/>Velikost: %s</center>" %(newFilename, desc, sizeTo))
	
	ui.listWidget.addItem(item)
	
	imageList.append(newPhoto)
	
	ui.imagePreview.clear();
	actualFilename = ""
	ui.addImageButton.setEnabled(False)
	ui.photoEdit.setText(u"")
	ui.photoEdit.setFocus()
	
	ui.titleEdit.setText(u"Titulek")
	ui.descEdit.setText(u"popis fotky")
	

def xchatLogin():
	global faInst
	faInst = Xchat()
	faInst.kernel.nick = ui.nickEdit.text()
	faInst.kernel.passwd = ui.passwdEdit.text()
	ui.nickEdit.setEnabled(False)
	ui.passwdEdit.setEnabled(False)
	ui.loginButton.setEnabled(False)
	ui.rememberBox.setEnabled(False)
	ui.errorLabel1.setText(u"Přihlašuji...")
	if faInst.login():
		ui.errorLabel1.setText(u"Stahuji přehled alb...")
		faInst.initFa()
		faInst.getLimits()
		faInst.getAlbums()
		albums = faInst.kernel.albums
		for album in albums:
			ui.albumBox.addItem(album[1].decode("iso-8859-2").replace("&amp;","&"))
		ui.errorLabel1.setText(u"%.2f MB z %.2f MB" %(float(faInst.kernel.uploaded)/(1024*1024), float(faInst.kernel.limit)/(1024*1024)))
		ui.taby.setCurrentIndex(1)
		ui.browseButton.setFocus()
	else:
		ui.nickEdit.setEnabled(True)
		ui.passwdEdit.setEnabled(True)
		ui.loginButton.setEnabled(True)
		ui.rememberBox.setEnabled(True)
		ui.errorLabel1.setText(u"<b>Neplatné přihlašovací jméno nebo heslo.</b>")


if __name__ == "__main__":
	app = QtGui.QApplication(sys.argv)
	window = QtGui.QDialog()
	ui = Ui_fotoalba_main()
	ui.setupUi(window)
	ui.taby.setCurrentIndex(0) # Set up first tab
	ui.rememberBox.setEnabled(False) # Not implemented yet
	ui.photoEdit.__class__.dropEvent = tryBrowseImage
	window.connect(ui.browseButton, QtCore.SIGNAL("clicked()"), browseImage)
	window.connect(ui.loginButton, QtCore.SIGNAL("clicked()"), xchatLogin)
	window.connect(ui.uploadButton, QtCore.SIGNAL("clicked()"), upload)
	
	window.connect(ui.nickEdit, QtCore.SIGNAL("returnPressed()"), xchatLogin)
	window.connect(ui.passwdEdit, QtCore.SIGNAL("returnPressed()"), xchatLogin)
	
	window.connect(ui.addImageButton, QtCore.SIGNAL("clicked()"), acceptImage)
	
	#window.connect(ui.albumBox, QtCore.SIGNAL("currentIndexChanged()"), changeAlbum)
	
	window.show()
	sys.exit(app.exec_())